package lv

import (
	"xr-game-server/core/constants/cmd"
	"xr-game-server/core/event"
	"xr-game-server/core/push"
	"xr-game-server/dao/roledao"
	"xr-game-server/gamecfg"
	"xr-game-server/gameevent"
)

// InitLv 等级模块只能通过物品模块操作,物品模块可以日志追踪
func InitLv() {
	initPropHandler()
	initItemHandler()
}

func add(roleId uint64, exp uint64, canPush bool) {
	roleData := roledao.GetRoleByRole(roleId)
	//获取当前等级
	currentLv := roleData.Level
	//当前经验
	currentExp := roleData.Exp
	maxLvCfg := gamecfg.GetMaxLv()
	//判断当前经验是否最大
	if currentExp >= maxLvCfg.Exp {
		return
	}
	roleData.AddExp(exp, maxLvCfg.Exp)
	//发送经验变更事件
	expEventData := gameevent.NewExpAddEventData(roleId, currentExp, roleData.Exp)
	event.Pub(gameevent.ExpAddEvent, expEventData)
	if canPush {
		//推送经验变更
		push.Data(roleId, cmd.ExpAdd, expEventData)
	}

	lvCfgs := gamecfg.GetLvs()
	lvSize := len(lvCfgs)
	//判断最大等级
	if currentLv >= maxLvCfg.Lv {
		return
	}
	for i := 0; i < lvSize; i++ {
		if roleData.Exp < lvCfgs[i].Exp {
			//处于当前等级
			if currentLv == lvCfgs[i].Lv {
				return
			}
			roleData.SetLevel(lvCfgs[i].Lv)
			//发送等级变更事件
			lvEventData := gameevent.NewLvAddEventData(roleId, currentLv, roleData.Level)
			event.Pub(gameevent.LvAddEvent, lvEventData)
			if canPush {
				push.Data(roleId, cmd.LvAdd, lvEventData)
			}
			return
		}
	}
}

func reduce(roleId uint64, exp uint64, canPush bool) bool {
	roleData := roledao.GetRoleByRole(roleId)
	if !roleData.CanReduceExp() {
		return false
	}
	currentExp := roleData.Exp
	roleData.ConsumeExp(exp)
	//发布经验减少事件
	expEventData := gameevent.NewExpReduceEventData(roleId, currentExp, roleData.Exp)
	event.Pub(gameevent.ExpReduceEvent, expEventData)
	if canPush {
		//推送经验减少
		push.Data(roleId, cmd.ExpReduce, expEventData)
	}
	maxLvCfg := gamecfg.GetMaxLv()
	//判断当前经验是否最大
	if currentExp >= maxLvCfg.Exp {
		return true
	}
	//获取当前等级
	currentLv := roleData.Level
	lvCfgs := gamecfg.GetLvs()
	lvSize := len(lvCfgs)

	for i := 0; i < lvSize; i++ {
		if roleData.Exp < lvCfgs[i].Exp {
			//处于当前等级
			if currentLv == lvCfgs[i].Lv {
				return true
			}
			roleData.SetLevel(lvCfgs[i].Lv)
			//发送等级变更事件
			lvEventData := gameevent.NewLvReduceEvent(roleId, currentLv, roleData.Level)
			event.Pub(gameevent.LvReduceEvent, lvEventData)
			if canPush {
				//推送等级变更
				push.Data(roleId, cmd.LvReduce, lvEventData)
			}
			return true
		}
	}
	return true
}
